package com.heima.search.listener;

import com.alibaba.fastjson.JSON;
import com.heima.model.search.vos.SearchArticleVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
public class ArticleIndexUpdateListener {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @KafkaListener(topics = "es.index.update")
    public void listener(String message) throws IOException {
        if(StringUtils.isBlank(message)){
            return;
        }

        log.info("监听到了消息"+message);

        SearchArticleVo searchArticleVo = JSON.parseObject(message, SearchArticleVo.class);
        IndexRequest indexRequest = new IndexRequest();
        indexRequest.id(searchArticleVo.getId().toString()).source(JSON.toJSONString(searchArticleVo));
        restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
    }
}
